package com.leftshine.dnstest.NetworkUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.LinkedList;

public class ConnectivityUtil {
    public static String getNetworkInfo(Context context){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Network currentNetwork = connectivityManager.getActiveNetwork();
            NetworkCapabilities caps = connectivityManager.getNetworkCapabilities(currentNetwork);
            LinkProperties linkProperties = connectivityManager.getLinkProperties(currentNetwork);
            return caps.toString() + "\n" +linkProperties.toString();
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            LinkProperties linkProperties = null;
            try {
                Class connectivityManagerClz = connectivityManager.getClass();
                Method[] methods = connectivityManagerClz.getMethods();
                Method methodGetActiveLinkProperties = connectivityManagerClz.getMethod("getActiveLinkProperties");
                linkProperties = (LinkProperties) methodGetActiveLinkProperties.invoke(connectivityManager);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return (networkInfo == null ? "" : networkInfo.toString()) + "\n" + (linkProperties == null ? "" : linkProperties.toString());
        }
    }

    public static class DnsUtil {

        /**
         * 获取dns
         *
         * @param context
         * @return
         */
        public static String getDns(Context context) {
            /**
             * 获取dns
             */
            String[] dnsServers = getDnsFromCommand();
            if (dnsServers == null || dnsServers.length == 0) {
                dnsServers = getDnsFromConnectionManager(context);
            }
            return Arrays.toString(dnsServers);
    //        /**
    //         * 组装
    //         */
    //        StringBuffer sb = new StringBuffer();
    //        if (dnsServers != null) {
    //            for (int i = 0; i < dnsServers.length; i++) {
    //                sb.append(dnsServers[i]);
    //                sb.append("");
    //            }
    //        }
    //        //
    //        return sb.toString();
        }


        //通过 getprop 命令获取
        private static String[] getDnsFromCommand() {
            LinkedList<String> dnsServers = new LinkedList<>();
            try {
                Process process = Runtime.getRuntime().exec("getprop");
                InputStream inputStream = process.getInputStream();
                LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inputStream));
                String line = null;
                while ((line = lnr.readLine()) != null) {
                    int split = line.indexOf("]: [");
                    if (split == -1) continue;
                    String property = line.substring(1, split);
                    String value = line.substring(split + 4, line.length() - 1);
                    if (property.endsWith(".dns")
                            || property.endsWith(".dns1")
                            || property.endsWith(".dns2")
                            || property.endsWith(".dns3")
                            || property.endsWith(".dns4")) {
                        InetAddress ip = InetAddress.getByName(value);
                        if (ip == null) continue;
                        value = ip.getHostAddress();
                        if (value == null) continue;
                        if (value.length() == 0) continue;
                        dnsServers.add(value);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
        }

        private static String[] getDnsFromConnectionManager(Context context) {
            LinkedList<String> dnsServers = new LinkedList<>();
            if (Build.VERSION.SDK_INT >= 21 && context != null) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
                if (connectivityManager != null) {
                    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                    if (activeNetworkInfo != null) {
                        for (Network network : connectivityManager.getAllNetworks()) {
                            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                            if (networkInfo != null && networkInfo.getType() == activeNetworkInfo.getType()) {
                                LinkProperties lp = connectivityManager.getLinkProperties(network);
                                for (InetAddress addr : lp.getDnsServers()) {
                                    dnsServers.add(addr.getHostAddress());
                                }
                            }
                        }
                    }
                }
            }
            return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
        }

    }
}
